import pymysql


class MysqlDataBases:
    def __init__(self):
        # 打开数据库连接
        self.conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', charset='utf8',
                               database='ssm')
        # 使用 cursor() 方法创建一个游标对象 cursor
        self.cursor = self.conn.cursor()

    # 登录方法
    def check_login(self,username,password):
        self.cursor.execute("select * from user")
        for user in self.cursor.fetchall():
            if username==user[1] and password==user[2]:
                return True,'登录成功'
        return False,'用户名或密码错误'
    # 获取所有信息
    def all(self):
        self.cursor.execute("select * from user")
        return self.cursor.fetchall()
    # 添加数据
    def insert(self,student):
        sql='insert into user values(%s,%s,%s)'
        params=(None,student.get('username'), student.get('password'))
        self.cursor.execute(sql,params)
        self.conn.commit()
    # 单个查询
    def one(self,username):
        sql='select * from user where username=%s'
        params = (username)
        self.cursor.execute(sql, params)
        student=self.cursor.fetchone()
        return student
    # 修改数据
    def update(self,student):
        sql='update user set password=%s where username=%s'
        params = (student.get('password'),student.get('username'))
        self.cursor.execute(sql, params)
        student=self.cursor.fetchone()
        self.conn.commit()
    # 删除数据
    def delete(self,username):
        student=db.one(username)
        if student!=None:
            sql = 'delete from user where username=%s'
            params = (username)
            self.cursor.execute(sql, params)
            self.conn.commit()
            return True
        return False

    # 关闭连接
    def close(self):
        self.cursor.close()

db=MysqlDataBases()
if __name__=='__main__':
    print(db.check_login('admin', '123456'))
    print(db.all())
    db.insert((None,'阿萨德','123456'))
    print(db.all())
    db.close()

